package com.googlecode.jvmpart.proc.regex;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.googlecode.jvmpart.proc.JvmProcess;
import com.googlecode.jvmpart.proc.JvmProcessException;
import com.googlecode.jvmpart.utils.URLUtils;


public abstract class URLContentProcessor extends RegexProcessor {
	private static final Log logger = LogFactory.getLog(URLContentProcessor.class);
	private static Pattern pattern = Pattern.compile("<title>([^<]+?)</title>",Pattern.CASE_INSENSITIVE);
	private String title;
	public String getTitle() {
		return title;
	}
	@Override
	public String regexContent(Map<String, String> params) throws JvmProcessException {
		String url = params.get(JvmProcess.PARAM_URL);
		try {
			String content = URLUtils.retrieve(url);
			Matcher mat = pattern.matcher(content);
			if(mat.find()) title = mat.group(1).trim();
			return content;
		} catch(Throwable e) {
			throw new JvmProcessException("download err:"+url, e);
		}
	}
	@Override
	public boolean whenError(Throwable t) {
		logger.warn(t, t);
		return true;
	}
	@Override
	public void completed() {
		
	}

}
